package com.wang.commom.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @Author: tiger
 * @Data: 2024/10/14 23:29
 * @Description: spring工具类 方便在非spring管理环境中获取bean
 * TODO - SpringUtils -不懂
 **/

@Component
public class SpringUtils implements BeanFactoryPostProcessor, ApplicationContextAware {


    /**
     * Spring应用上下文环境
     */
    private static ConfigurableListableBeanFactory beanFactory;

    private static ApplicationContext applicationContext;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println("tiger-common-data-SpringUtils-postProcessBeanFactory");
        SpringUtils.beanFactory = beanFactory;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }

    /**
     * @MethodName: getBean
     * @Param: [cls]
     * @Return: T
     * @Date: 2024/10/14 23:40
     * @Description: 根据类对象获取Bean对象
     **/
    public static <T> T getBean(Class<T> cls) {
        T result = (T) beanFactory.getBean(cls);
        return result;
    }
}
